package com.gobo.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gobo.eduservice.listener.ExcelListener;
import com.gobo.eduservice.pojo.EduSubject;
import com.gobo.eduservice.mapper.EduSubjectMapper;
import com.gobo.eduservice.pojo.excel.SubjectUploadDemo;
import com.gobo.eduservice.pojo.vo.OneSubjectVo;
import com.gobo.eduservice.pojo.vo.TwoSubjecVo;
import com.gobo.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gobo.servicebase.handler.exception.pojo.GoboException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author gobo-generator
 * @since 2021-09-19
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveUpload(MultipartFile file, EduSubjectService subjectService) {
        try {
            InputStream inputStream = file.getInputStream();
            EasyExcel.read(inputStream, SubjectUploadDemo.class,new ExcelListener(subjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new GoboException(50003,"上传Excel添加课程异常！");
        }
    }

    @Override
    public List<OneSubjectVo> getAllSubject() {
        List<OneSubjectVo> list = new ArrayList<>();
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id","0");
        List<EduSubject> oneEduSubject = baseMapper.selectList(queryWrapper);
        QueryWrapper<EduSubject> queryWrapper2 = new QueryWrapper<>();
        queryWrapper.ne("parent_id","0");
        List<EduSubject> twoEduSubject = baseMapper.selectList(queryWrapper2);
        for (int i = 0; i < oneEduSubject.size(); i++) {
            OneSubjectVo oneSubjectVo = new OneSubjectVo();
            EduSubject eduSubject = oneEduSubject.get(i);
            BeanUtils.copyProperties(eduSubject,oneSubjectVo);
            String pid = oneSubjectVo.getId();
            List<TwoSubjecVo> list1 = new ArrayList<>();
            for (int j = 0; j < twoEduSubject.size(); j++) {
                EduSubject eduSubject1 = twoEduSubject.get(j);
                if (pid==eduSubject1.getId() || pid.equals(eduSubject1.getParentId())){
                    TwoSubjecVo twoSubjecVo = new TwoSubjecVo();
                    BeanUtils.copyProperties(eduSubject1,twoSubjecVo);
                    list1.add(twoSubjecVo);
                }
            }
            oneSubjectVo.setChildren(list1);
            list.add(oneSubjectVo);
        }
        return list;
    }
}
